package com.supreme.proxyserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.supreme.commonboot.utils.AjaxResp;
import com.supreme.proxyserver.feignsvc.BizOrderService;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Optional;

@RestController
@RequestMapping(value = "remote")
public class RemoteController {

    @Resource
    private RestTemplate cloudRestTemplate;

    @Resource
    private BizOrderService bizOrderService;

    @GetMapping(value = "bizOrderSvcOrderList")
    public AjaxResp bizOrderSvcOrderList() {
        String url = "http://supreme-biz-order-server/api/order/orders";
        final StopWatch stopWatch = new StopWatch("bizOrderSvc");
        stopWatch.start("orders");
        JSONObject forObject = cloudRestTemplate.getForObject(url, JSONObject.class);
        stopWatch.stop();
        final long totalTimeMillis = stopWatch.getTotalTimeMillis();
        System.out.println("totalTimeMillis = " + totalTimeMillis + " ms");
        Object result = Optional.ofNullable(forObject)
                .map(jsonObject -> jsonObject.get("data"))
                .orElse(null);
        return AjaxResp.instance(result);
    }

    @GetMapping(value = "bizOrderFeignOrderList")
    public AjaxResp bizOrderFeignOrderList() {
        final StopWatch stopWatch = new StopWatch("bizOrderSvc");
        stopWatch.start("orders");
        final AjaxResp orderList = bizOrderService.getOrderList();
        stopWatch.stop();
        final long totalTimeMillis = stopWatch.getTotalTimeMillis();
        System.out.println("totalTimeMillis = " + totalTimeMillis + " ms");
        Object result = Optional.ofNullable(orderList.getData())
                .map(data -> orderList.getData())
                .orElse(null);
        return AjaxResp.instance(result);
    }
}
